import { MyEditor } from '@packages/Editor';
import { goEditArticle } from '@/utils/route.util';
import { Button, Layout, Menu, MenuProps, message } from 'antd';
import { Content, Header } from 'antd/es/layout/layout';
import styles from '@/pages/editor/index.less';
import React, { useEffect, useState } from 'react';
import Sider from 'antd/es/layout/Sider';
import { ArticleModel } from '@/models/article.model';
import { addArticle, delArticle, getAllArticle } from '@/services/article.server';

const App = () => {
  const [articles, setArticles] = useState<ArticleModel[]>([]);
  const [curArticle, setCurArticle] = useState<ArticleModel>();
  useEffect(() => {
    getAllArticle().then((res) => {
      console.log(res, 'articles');
      setArticles(res);
      setCurArticle(res[0]);
    });
  }, []);
  const delTargetArt = (id: number) => {
    delArticle(id).then(() => {
      message.success('删除成功');
      setArticles(articles.filter((item) => item.id !== id));
    });
  };

  const items2: MenuProps['items'] = articles.map((item) => {
    return {
      key: `sub${item.id}`,
      icon: (
        <div style={{ height: '20px', width: '20px', background: 'red', borderRadius: '50%' }} />
      ),
      label: (
        <span className={styles.slidItem} onClick={() => setCurArticle(item)}>
          {`subnav ${item.id}`}
          <button onClick={() => delTargetArt(item.id)}>删除</button>
        </span>
      ),
    };
  });

  const jumpToEdit = () => {
    if (!curArticle?.id) {
      message.warn('文章Id不存在');
      return;
    }
    goEditArticle(curArticle.id);
  };

  const addNewArticle = () => {
    addArticle().then((res) => {
      goEditArticle(res.id);
    });
  };

  return (
    <Layout>
      <Header>
        <Button onClick={() => jumpToEdit()} className={'margin-1'}>
          去编辑
        </Button>
        <Button onClick={() => addNewArticle()} className={'margin-1'}>
          新增
        </Button>
      </Header>
      <Layout hasSider>
        <Sider className={styles.viewSlider}>
          <Menu mode="inline" style={{ height: '100%', borderRight: 0 }} items={items2} />
        </Sider>
        <Content className={styles.editContent}>
          <MyEditor content={curArticle?.content || ''} />
        </Content>
      </Layout>
    </Layout>
  );
};

export default App;
